import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:wowhy/service_locator.dart';
import 'package:wowhy/services/navigate_service.dart';

import '../../services/auth_service.dart';

import 'action.dart';
import 'state.dart';

Effect<MePageState> buildEffect() {
  return combineEffects(<Object, Effect<MePageState>>{
    Lifecycle.initState: _onInit,
    MePageAction.onLogin: _onLogin,
    MePageAction.onLogout: _onLogout,
  });
}

void _onInit(Action action, Context<MePageState> ctx) async {
  MePageState state =
      MePageState(isLogined: await AuthService.instance.isLogined());
  ctx.dispatch(MePageActionCreator.init(state));
}

void _onLogin(Action action, Context<MePageState> ctx) async {
  dynamic result = await getIt<NavigateService>().pushNamed('login');
  if (result != null && result is bool) {
    ctx.dispatch(MePageActionCreator.login(result));
  }
}

void _onLogout(Action action, Context<MePageState> ctx) async {
  await AuthService.instance.logout();
  ctx.dispatch(MePageActionCreator.login(false));
}
